﻿using mshtml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AliMaMaLogin
{
    
    public partial class Form1 : Form
    {
        string Id = "2757189408";
        public Form1()
        {
            InitializeComponent();
        }

        private void RunJs(string jscode) {
            var doc = wbMain.Document.DomDocument as IHTMLDocument2;
            var win = doc.parentWindow as IHTMLWindow2;
            win.execScript(jscode, "javascript");
        }
        private void log(string log) {
            tblog.Text += log+"\n";
        }
        private void wbMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //文档加载完成

            bool flag2 = e.Url.ToString().StartsWith("https://login.taobao.com/member/login.jhtml");
            if (flag2)
            {
                new Thread(delegate ()
                {
                    try
                    {
                        Thread.Sleep(3000);
                        base.Invoke(new MethodInvoker(delegate ()
                        {
                            RunJs("function login(){var autologin=false;for(var i=0;i<document.getElementsByClassName('item-sso-user').length;i++){if(document.getElementsByClassName('item-sso-user')[i].getElementsByClassName('user-name')[0].innerHTML=='" + this.Id + "'){autologin=true;var e = document.createEvent('MouseEvent'); e.initEvent('click', true, false); document.getElementsByClassName('item-sso-user')[i].dispatchEvent(e);document.getElementById('J_SubmitQuick').click();alert('autologin')}}if(!autologin){alert(document.getElementsByClassName('login-msg')[0].getElementsByClassName('error')[0].innerHTML)}};setTimeout(\"login()\",1000)");
                        }));
                    }
                    catch (Exception ex2)
                    {
                    }
                })
                {
                    IsBackground = true
                }.Start();
            }
            else
            {
                bool flag3 = e.Url.ToString().StartsWith("http://www.alimama.com/") || e.Url.ToString().StartsWith("https://www.alimama.com/");
                if (flag3)
                {
                    string cookie = wbMain.Document.Cookie;
                    Match match = Regex.Match(cookie, "_tb_token_\\=([^;]{5,});", RegexOptions.IgnoreCase);
                    bool success = match.Success;
                    if (success)
                    {
                        log("--Alimama-Cookie：" + cookie);
                        log("--Alimama-Token：" + match.Groups[1].Value.Trim());
                        //Console.WriteLine("Login:Success");
                    }
                    else
                    {
                        MessageBox.Show("阿里妈妈登录失败,请重试:Token读取失败");
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0";
            UserAgentHelper.ChangeUserAgent(ua);
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            wbMain.Url = new Uri("https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&from=alimama&redirectURL=http%3A%2F%2Flogin.taobao.com%2Fmember%2Ftaobaoke%2Flogin.htm%3Fis_login%3d1&full_redirect=true");
        }
    }
    public class UserAgentHelper
    {
        private static string defaultUserAgent = null;
        [DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
        private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
        const int URLMON_OPTION_USERAGENT = 0x10000001;
        /// <summary> 
        /// 在默认的UserAgent后面加一部分 
        /// </summary> 
        public static void AppendUserAgent(string appendUserAgent)
        {
            if (string.IsNullOrEmpty(defaultUserAgent))
                defaultUserAgent = GetDefaultUserAgent();
            string ua = defaultUserAgent+";"+appendUserAgent;
            ChangeUserAgent(ua);
        }
        /// <summary> 
        /// 修改UserAgent 
        /// </summary> 
        public static void ChangeUserAgent(string userAgent)
        {
            UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0);
        }
        /// <summary> 
        /// 一个很BT的获取IE默认UserAgent的方法 
        /// </summary> 
        private static string GetDefaultUserAgent()
        {
            WebBrowser wb = new WebBrowser();
            wb.Navigate("about:blank");
            while (wb.IsBusy) Application.DoEvents();
            object window = wb.Document.Window.DomWindow;
            Type wt = window.GetType();
            object navigator = wt.InvokeMember("navigator", BindingFlags.GetProperty,
                null, window, new object[] { });
            Type nt = navigator.GetType();
            object userAgent = nt.InvokeMember("userAgent", BindingFlags.GetProperty,
                null, navigator, new object[] { });
            return userAgent.ToString();
        }
    }
}
